<template>
  <div class="video-crop-container">
    <div class="video-container" ref="videoContainerRef">
      <div class="video-real-size" ref="videoWrapper">
        <video
          ref="videoPlayer"
          :src="videoUrl"
          @loadedmetadata="getVideoDimensions"
          class="video"
          :controls="false"
        ></video>
        <VueDragResize
          v-for="(box, index) in boxes"
          :key="`box-${box.id}-${box.forceKey}`"
          :x="box.visibleX"
          :y="box.visibleY"
          :w="box.width"
          :isActive="box.isActive"
          :h="box.height"
          :parentLimitation="true"
          @dragging="handleDrag($event, index)"
          @resizing="handleResize($event, index)"
          @clicked.stop="(e) => handleBoxClick(e, box)"
          @deactivated="() => handleBoxDeactivate(index)"
          class="drag-box"
        >
          <div class="box-label" v-if="boxes.length > 1">X</div>
        </VueDragResize>
      </div>
    </div>
    <div class="crop-ratio-box">
      <div class="video-controls">
        <!-- 播放/暂停控制 -->
        <div class="control-btn" @click="togglePlay">
          <pause-circle-filled v-if="isPlaying" />
          <play-circle-filled v-else />
        </div>
        <!-- 进度条 -->
        <div class="progress-container" ref="progressContainer" @click="seek">
          <div
            ref="startBtnRef"
            class="trim-handle start-handle"
            :style="{ left: starBtntLeft }"
            @mousedown="startDrag"
          ></div>
        </div>
        <div class="time-display">
          <span class="ml-5">
            {{ formatTime(currentTime) }} /
            {{ formatTime(videoDuration) }}</span
          >
        </div>
      </div>
      <div class="flex justify-between align-center w-full mt-10 py-10">
      <div>
        <span v-if="numUnitValue&&numConsumesValue&&nameValue" class="coast-tip">每{{numUnitValue}}消耗{{pointConsumesValue}}{{pointUnitValue}}{{ nameValue }}, 不足1{{numUnitValue}}按1{{numUnitValue}}计算</span>
      </div>
        <div class="flex">
          <a-button type="primary" @click="addBox" :disabled="boxes.length >1"
          >添加拆除选框</a-button
        >
        <div>
          <a-button
            class="ml-5"
            type="primary"
            @click="startCrop"
            :loading="loading"
            >开始处理</a-button
          >
          <a-button class="ml-5" @click="cancelCrop">取消</a-button>
        </div>
        </div>
      </div>
    </div>
    <div class="mask" v-if="loading">
      <div class="loading">
        <span>处理中...</span>
      </div>
    </div>
  </div>
</template>
<script setup>
import VueDragResize from "vue-drag-resize/src";
import {
  LoadingOutlined,
  PauseCircleFilled,
  PlayCircleFilled,
  CloseCircleOutlined,
} from "@ant-design/icons-vue";
import { ref, reactive, computed, watch, onMounted, nextTick } from "vue";
import videoControl from "../components/VideoControl.vue";
import { getComputingPowerDetail } from "../utils/index.js";
import { v4 as uuidv4 } from "uuid";
const props = defineProps({
  videoUrl: {
    type: String,
    default: "",
  },
  loading: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["cancelCrop", "startCrop"]);
// 获取视频的原始宽高
let videoPlayer = ref();
let videoRealWidth = ref(0);
let videoRealHeight = ref(0);
let videoCssWdith = ref(0);
let videoCssHeight = ref(0);
let videoContainerRef = ref();
let videoDuration = ref(0);
let videoControlRef = ref();
let duration = ref(0);
let currentTime = ref(0);
let progressContainer = ref();
let starBtntLeft = ref("0%");
let numUnitValue = ref("");
let numConsumesValue = ref("");
let pointConsumesValue = ref("");
let nameValue = ref("");
let pointUnitValue = ref("");

// 新增响应式数据
const videoWrapper = ref(null);

let isPlaying = ref(false);
const crop_box_data = reactive({
  width: 0,
  height: 0,
  x: 0,
  y: 0,
});
// 检测两个矩形是否碰撞
const isColliding = (rect1, rect2) => {
  return !(
    rect1.right <= rect2.left ||
    rect1.left >= rect2.right ||
    rect1.bottom <= rect2.top ||
    rect1.top >= rect2.bottom
  );
};
// 生成一个不碰撞的位置
const generateRadomPostion = (width, height) => {
  let parentWidth = videoWrapper.value.offsetWidth;
  let parentHeight = videoWrapper.value.offsetHeight;
  const maxAttempts = 100; // 最大尝试次数
  let attempts = 0;
  while (attempts < maxAttempts) {
    // 随机生成位置
    const x = Math.floor(Math.random() * (parentWidth - width));
    const y = Math.floor(Math.random() * (parentHeight - height));
    // 创建临时矩形
    const tempRect = {
      left: x,
      right: x + width,
      top: y,
      bottom: y + height,
    };
    // 检测是否与已有元素碰撞
    const collision = boxes.some((box) => {
      const boxRect = {
        left: box.visibleX,
        right: box.visibleX + box.width,
        top: box.visibleY,
        bottom: box.visibleY + box.height,
      };
      return isColliding(tempRect, boxRect);
    });
    // 如果未碰撞，返回位置
    if (!collision) {
      return { x, y };
    }
    attempts++;
  }
  // 如果超过最大尝试次数，抛出错误
  throw new Error("无法找到不碰撞的位置，请调整父元素大小或已有元素布局。");
};

const boxes = reactive([
  {
    id: 1,
    realX: 0, // 持久化合法X坐标
    realY: 0, // 持久化合法Y坐标
    visibleX: 0, // 可视化临时X坐标
    visibleY: 0, // 可视化临时Y坐标
    width: 100,
    height: 100,
    visibleWidth: 100, // 可视化临时宽度
    visibleHeight: 100, // 可视化临时高度
    forceKey: 0, // 强制刷新标识
    isColliding: false,
    isActive: true, // 激活状态
  },
]);

const removeBox = (id) => {
  boxes.splice(
    boxes.findIndex((box) => box.id === id),
    1
  );
};
// 添加新元素
const addBox = () => {
  const newWidth = 100; // 新元素的宽度
  const newHeight = 100; // 新元素的高度
  try {
    // 生成不碰撞的位置
    const { x, y } = generateRadomPostion(newWidth, newHeight);
    boxes.forEach((box) => {
      box.isActive = false;
    });
    // 添加新元素
    boxes.push({
      id: uuidv4(), // 生成唯一ID
      realX: x, // 持久化合法X坐标
      realY: y, // 持久化合法Y坐标
      visibleX: x, // 可视化临时X坐标
      visibleY: y, // 可视化临时Y坐标
      width: newWidth,
      height: newHeight,
      visibleWidth: newWidth, // 可视化临时宽度
      visibleHeight: newHeight, // 可视化临时高度
      forceKey: 0, // 强制刷新标识
      isColliding: false,
      isActive: true, // 激活状态
    });
  } catch (error) {
    console.error(error.message);
  }
};

// 格式化时间显示
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  seconds = Math.floor(seconds % 60);
  return `${minutes}:${seconds.toString().padStart(2, "0")}`;
};
/**
 * 将CSS尺寸坐标转换到原始视频尺寸坐标系
 * @param {Object} cssCrop  CSS尺寸的裁剪参数 {x, y, width, height}
 * @param {number} videoCssWidth  视频在页面中的实际渲染宽度
 * @param {number} videoCssHeight 视频在页面中的实际渲染高度
 * @param {number} videoRealWidth  视频原始宽度
 * @param {number} videoRealHeight 视频原始高度
 * @returns {Object} 原始视频坐标系中的参数
 */
function convertCropToOriginal(
  cssCrop,
  videoCssWidth,
  videoCssHeight,
  videoRealWidth,
  videoRealHeight
) {
  // 核心计算逻辑
  const scaleX = videoCssWidth / videoRealWidth;
  const scaleY = videoCssHeight / videoRealHeight;

  // 比例容错处理（保护非标准缩放模式）
  if (Math.abs(scaleX - scaleY) > 0.01) {
    console.warn("非等比缩放模式，转换结果可能不准确");
  }

  let scaleX_int = scaleX.toFixed(3);
  let scaleY_int = scaleY.toFixed(3);

  // 计算反向映射
  return {
    x: Math.floor(cssCrop.x / scaleX_int),
    y: Math.floor(cssCrop.y / scaleY_int),
    w: Math.floor(cssCrop.width / scaleX_int),
    h: Math.floor(cssCrop.height / scaleY_int),
  };
}

const startCrop = () => {
  const videoCssWdith = videoPlayer.value.offsetWidth;
  const videoCssHeight = videoPlayer.value.offsetHeight;
  const videoRealWidth = videoPlayer.value.videoWidth;
  const videoRealHeight = videoPlayer.value.videoHeight;

  // 遍历所有框，将CSS尺寸坐标转换到原始视频尺寸坐标系
  let data = boxes.map((item) => {
    return convertCropToOriginal(
          {
          x: item.visibleX,
          y: item.visibleY,
          width: item.width,
          height: item.height,
        },
        videoCssWdith,
        videoCssHeight,
        videoRealWidth,
        videoRealHeight
      );
  });
  emit("startCrop", data);
};
const cancelCrop = () => {
  emit("cancelCrop");
};
const togglePlay = () => {
  if (videoPlayer.value.paused) {
    videoPlayer.value.play();
    isPlaying.value = true;
  } else {
    videoPlayer.value.pause();
    isPlaying.value = false;
  }
};
// 拖动处理
const onDrag = (event) => {
  if (!videoPlayer.value.paused) {
    videoPlayer.value.pause();
    isPlaying.value = false;
  }
  const rect = progressContainer.value.getBoundingClientRect();
  const offsetX = event.clientX - rect.left;
  const newTime = (offsetX / rect.width) * videoDuration.value;
  if (newTime < videoDuration.value && newTime > 0) {
    starBtntLeft.value = `${(offsetX / rect.width) * 100}%`;
    currentTime.value = newTime;
    videoPlayer.value.currentTime = currentTime.value; // 设置视频播放时间
  }
};
// 停止拖动
const stopDrag = () => {
  document.removeEventListener("mousemove", onDrag);
  document.removeEventListener("mouseup", stopDrag);
  videoPlayer.value.pause();
  isPlaying.value = false;
  // 处理拖动结到视频结尾时间小数点问题
  if (Math.floor(currentTime.value) === Math.floor(videoDuration.value)) {
    currentTime.value = videoDuration.value;
    videoPlayer.value.currentTime = currentTime.value;
  }
};
const startDrag = () => {
  document.addEventListener("mousemove", onDrag);
  document.addEventListener("mouseup", stopDrag);
};

function autoFitContainer(parentWidth, parentHeight, childWidth, childHeight) {
  // 边界检查
  if (parentWidth <= 0 || parentHeight <= 0) {
    throw new Error("Invalid container dimensions");
  }
  if (childWidth <= 0 || childHeight <= 0) {
    return { width: parentWidth, height: parentHeight }; // 返回最大尺寸
  }
  // 计算宽高比
  const containerRatio = parentWidth / parentHeight;
  const childRatio = childWidth / childHeight;
  // 根据宽高比关系动态选择缩放方向
  let targetWidth, targetHeight;

  if (childRatio > containerRatio) {
    // 水平方向填满，垂直居中
    targetWidth = parentWidth;
    targetHeight = parentWidth / childRatio;
  } else {
    // 垂直方向填满，水平居中
    targetHeight = parentHeight;
    targetWidth = parentHeight * childRatio;
  }
  // 返回整数尺寸
  return { width: Math.round(targetWidth), height: Math.round(targetHeight) };
}

const initCropBoxData = async () => {
  let parentWidth = videoContainerRef.value.offsetWidth;
  let parentHeight = videoContainerRef.value.offsetHeight;
  let videoRealWidth = videoPlayer.value.videoWidth;
  let videoRealHeight = videoPlayer.value.videoHeight;
  let { width: finalParentWidth, height: finalParentHeight } = autoFitContainer(
    parentWidth,
    parentHeight,
    videoRealWidth,
    videoRealHeight
  );
  videoCssWdith.value = finalParentWidth + "px";
  videoCssHeight.value = finalParentHeight + "px";
};

const getVideoDimensions = () => {
  initCropBoxData();
  boxes.forEach((box) => {
    box.forceKey += 1; // 强制更新
  });
  videoDuration.value = videoPlayer.value.duration;
  videoPlayer.value.addEventListener("timeupdate", () => {
    currentTime.value = videoPlayer.value.currentTime;
    starBtntLeft.value = (currentTime.value / videoDuration.value) * 100 + "%";

    // 如果视频结束，播放结束
    if (currentTime.value >= videoDuration.value) {
      isPlaying.value = false;
      currentTime.value = videoDuration.value;
    }
  });
};

const handleBoxDeactivate = (index) => {
  boxes[index].isActive = false;
};
const handleBoxClick = (e, box) => {
  // 判断点击事件是否来自关闭按钮
  if (e.target.closest(".box-label")) {
    removeBox(box.id); // 调用删除方法
    return;
  }

  boxes.forEach((box) => {
    box.isActive = false;
  });
  let index = boxes.findIndex((item) => item.id === box.id);
  boxes[index].isActive = true;
};

const handleDrag = (position, index) => {
  // 强制整数像素定位
  const newX = Math.round(position.left);
  const newY = Math.round(position.top);

  // 更新临时坐标
  boxes[index].visibleX = newX;
  boxes[index].visibleY = newY;
};


const handleResize = (newSize, index) => {
  const box = boxes[index];
//   // 像素对齐处理
  const alignedWidth = Math.round(newSize.width);
  const alignedHeight = Math.round(newSize.height);
  const alignedX = Math.round(newSize.left);
  const alignedY = Math.round(newSize.top);

 // 更新临时尺寸和位置
  Object.assign(box, {
    visibleX: alignedX,
    visibleY: alignedY,
    width: alignedWidth,
    height: alignedHeight,
  });
};
getComputingPowerDetail({key:'extract_video_erasure_logo_point'}).then((res) => {
  if (res) {
    let {
      numberInfo:{unit:numUnit,consumes:numConsumes},
      pointInfo:{unit:pointUnit,consumes:pointConsumes,name}
    } = res; 
    console.log(numUnit,numConsumes,pointConsumes,name,pointUnit);
    
    numUnitValue.value = numUnit;
    numConsumesValue.value = numConsumes;
    pointConsumesValue.value = pointConsumes;
    nameValue.value = name;
    pointUnitValue.value = pointUnit;
  } 
})
</script>
<style lang="less" scoped>
.video-crop-container {
  position: relative;
}

.video-container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 100%;
  height: 600px;
  background-color: rgba(0, 0, 0, 0.5);
}

.video-real-size {
  position: relative;
  width: v-bind(videoCssWdith);
  height: v-bind(videoCssHeight);
}

.video {
  position: relative;
  width: 100%;
  object-fit: contain;
}



.crop-ratio-box {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.mask {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  font-size: 16px;
  color: #fff;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  cursor: not-allowed;
  .loading {
    color: white;
    width: 120px;
    height: 120px;
    box-sizing: border-box;
    border-radius: 50%;
    border-top: 10px solid #e74c3c;
    position: relative;
    animation: a1 2s linear infinite;
  }
  .loading span {
    width: 120px;
    height: 120px;
    display: block;
    text-align: center;
    line-height: 120px;
    animation: a2 2s linear infinite;
  }
  .loading:before,
  .loading:after {
    content: "";
    width: 120px;
    height: 120px;
    position: absolute;
    left: 0;
    top: -10px;
    box-sizing: border-box;
    border-radius: 50%;
  }
  .loading:before {
    border-top: 10px solid lawngreen;
    transform: rotate(120deg);
  }
  .loading:after {
    border-top: 10px solid var(--ss-primary-color);
    transform: rotate(-120deg);
  }

  @keyframes a1 {
    to {
      transform: rotate(360deg);
    }
  }
  @keyframes a2 {
    to {
      transform: rotate(-360deg);
    }
  }
}
.video-controls {
  width: 100%;
  height: 50px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.6));
  display: flex;
  align-items: center;
  padding: 0 20px;
  gap: 15px;
  box-sizing: border-box;
  // z-index: 999;
  // margin-top: 3px;

  .control-btn {
    cursor: pointer;
    color: #fff;
    font-size: 28px;
    padding: 5px;
    transition: opacity 0.3s;

    &:hover {
      opacity: 0.8;
    }
  }

  .progress-container {
    flex: 1;
    position: relative;
    height: 4px;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 2px;
    cursor: pointer;
    &::before {
      content: "";
      position: absolute;
      top: 0;
      // transform: translateX(-50%);
      width: v-bind(starBtntLeft);
      height: 100%;
      background: #fff;
      left: 0;
      z-index: 1;
    }
  }

  .trim-handle {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;

    top: 50%;
    transform: translate(-50%, -50%);
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #fff;
    &:hover {
      opacity: 0.8;
    }
    cursor: all-scroll;
  }

  .time-display {
    color: #fff;
    font-size: 12px;
  }

  .volume-control {
    display: flex;
    align-items: center;
    gap: 8px;

    span {
      cursor: pointer;
    }

    .volume-slider {
      width: 80px;
      height: 3px;
      background: rgba(255, 255, 255, 0.3);
      appearance: none;

      &::-webkit-slider-thumb {
        appearance: none;
        width: 10px;
        height: 10px;
        background: #fff;
        border-radius: 50%;
      }
    }
  }
}

.vdr {
  outline: 1px solid #4caf50;
  background: rgba(76, 175, 80, 0.3);
  //   transition: all 0.3s;
}

.box-label {
  width: 20px;
  height: 20px;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  top: 5px;
  right: 5px;
  color: red;
  cursor: pointer;
  border-radius: 50%;
  background: #fff;
  display: none;
  transform: scale(0.8);
}
.close-btn {
  //  display: none;
  font-size: 16px;
  color: red;
  z-index: 999999999 !important;
}
.not-allowed {
  cursor: not-allowed;
}
.drag-box {
  cursor: move;
  :hover {
    z-index: 99999!important;
  }
  &:hover .box-label {
    display: flex;
  }
}
.coast-tip{
  color: #666;
}
</style>
